<?php

declare(strict_types=1);
/**
 * Author: Zane
 * Email: 873934580@qq.com
 * Date: 2023/5/30.
 */

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Http\Controllers\Traits\EditTrait;
use App\Http\Controllers\Traits\ExtendTrait;
use App\Http\Controllers\Traits\StoreTrait;
use App\Http\Controllers\Traits\ValidateTrait;
use App\Models\ConfigureCate;
use App\Utils\ResultsVo;
use Illuminate\Validation\Rule;

class ConfigureCateController extends Controller
{
    use EditTrait;
    use ExtendTrait;
    use StoreTrait;
    use ValidateTrait;

    public function index(): \Illuminate\Http\JsonResponse
    {
        $results = ConfigureCate::query()
            ->select(['id', 'parent_id', 'title', 'name', 'weight', 'remark', 'status'])
            ->get()->toArray();
        $results = infiniteTree($results);

        return ResultsVo::success(['results' => $results]);
    }

    protected function rules(): array
    {
        $id = (int) request()->route('id');
        $parentId = (int) request()->get('parent_id');

        return [
            'title' => ['required', 'max:255', Rule::unique(ConfigureCate::class)->ignore($id)],
            'name' => ['required', 'max:255', Rule::unique(ConfigureCate::class)->ignore($id)],
            'weight' => 'integer|min:0|max:255',
            'parent_id' => $parentId ? [Rule::exists(ConfigureCate::class, 'id')] : [],
            'remark' => 'max:255',
            'status' => 'in:0,1',
        ];
    }
}
